// js/data.js

// 模拟数据库数据 (使用 localStorage 持久化)
let users = [];
let outcomes = [];
let customOutcomeTypes = [];

// 默认的系统预设成果类型及其必填/选填字段定义
const defaultOutcomeTypes = [
    {
        id: 'paper',
        name: '论文',
        requiredFields: ['title', 'authors', 'journalConference', 'publishDate', 'projectSupport'],
        optionalFields: ['doi', 'issn', 'journalPartition', 'inclusionStatus', 'impactFactor'],
        authorship: true, // Indicates if 'authors' needs complex input (first/comm. author, unit)
        fieldLabels: {
            title: '标题',
            authors: '作者列表',
            journalConference: '发表期刊/会议 (等级)',
            publishDate: '发表时间',
            projectSupport: '项目支撑',
            doi: 'DOI',
            issn: 'ISSN',
            journalPartition: '期刊分区',
            inclusionStatus: '收录情况',
            impactFactor: '影响因子'
        },
        fieldPlaceholders: {
            title: '论文标题',
            journalConference: '如：Nature, SCI一区',
            publishDate: 'YYYY-MM-DD',
            doi: '如：10.1038/s41586-023-06670-3'
        },
        fieldTypes: {
            publishDate: 'date'
        },
        attachments: true
    },
    {
        id: 'patent',
        name: '专利',
        requiredFields: ['title', 'inventorsDesigners', 'patentNumber'],
        optionalFields: ['patentType', 'applicationDate', 'authorizationDate', 'affiliation'],
        authorship: true, // Indicates if 'inventorsDesigners' needs complex input
        fieldLabels: {
            title: '专利标题',
            inventorsDesigners: '发明人/设计人列表',
            patentNumber: '专利号',
            patentType: '专利类型',
            applicationDate: '申请日期',
            authorizationDate: '授权日期',
            affiliation: '成果所属部门/学院'
        },
        fieldPlaceholders: {
            title: '专利标题',
            patentNumber: '如：CN123456789U',
            applicationDate: 'YYYY-MM-DD',
            authorizationDate: 'YYYY-MM-DD',
            affiliation: '如：计算机学院'
        },
        fieldTypes: {
            applicationDate: 'date',
            authorizationDate: 'date'
        },
        dropdownOptions: {
            patentType: ['发明专利', '实用新型', '外观设计']
        },
        attachments: true
    },
    {
        id: 'competition',
        name: '竞赛',
        requiredFields: ['competitionName', 'competitionLevel', 'awardLevel', 'competitionType'],
        optionalFields: ['participants', 'myRank', 'awardDate'],
        fieldLabels: {
            competitionName: '竞赛名称',
            competitionLevel: '竞赛等级',
            awardLevel: '获奖等级',
            competitionType: '竞赛类型',
            participants: '参赛队员',
            myRank: '本人在参赛成员中的排名',
            awardDate: '获奖日期'
        },
        fieldPlaceholders: {
            competitionName: '如：全国大学生程序设计竞赛',
            awardDate: 'YYYY-MM-DD'
        },
        fieldTypes: {
            awardDate: 'date'
        },
        dropdownOptions: {
            competitionLevel: ['国家级', '省部级', '市厅级', '校级', '国际级'],
            competitionType: ['个人竞赛', '团队竞赛']
        },
        attachments: true
    },
    {
        id: 'researchProject',
        name: '科研项目',
        requiredFields: ['projectName', 'projectLeader', 'participantsRanked', 'projectLevel'],
        optionalFields: ['projectStatus', 'affiliation'],
        authorship: true, // Indicates if 'participantsRanked' needs complex input
        fieldLabels: {
            projectName: '项目名称',
            projectLeader: '项目负责人',
            participantsRanked: '参与成员及其排名',
            projectLevel: '项目级别',
            projectStatus: '项目状态',
            affiliation: '成果所属部门/学院'
        },
        fieldPlaceholders: {
            projectName: '如：国家自然科学基金项目',
            projectLeader: '项目负责人姓名',
            affiliation: '如：计算机学院'
        },
        dropdownOptions: {
            projectLevel: ['国家级', '省部级', '市厅级', '校级'],
            projectStatus: ['在研', '已结题', '中期检查通过', '延期', '终止']
        },
        attachments: true
    }
];

// --- 数据初始化与加载 ---
function loadData() {
    users = JSON.parse(localStorage.getItem('users')) || [
        { id: 'u001', username: 'admin', password: '123', role: 'admin' },
        { id: 'u002', username: 'user1', password: '123', role: 'normal' },
        { id: 'u003', username: 'user2', password: '123', role: 'normal' }
    ];
    outcomes = JSON.parse(localStorage.getItem('outcomes')) || [];
    customOutcomeTypes = JSON.parse(localStorage.getItem('customOutcomeTypes')) || [];

    // Ensure all default types are present if localStorage was empty or corrupted
    // This is a simplified merge, a real system would handle schema migrations
    defaultOutcomeTypes.forEach(defaultType => {
        if (!customOutcomeTypes.some(ct => ct.id === defaultType.id)) {
            customOutcomeTypes.push(defaultType);
        }
    });

    console.log("Data loaded:", { users, outcomes, customOutcomeTypes });
}

function saveData() {
    localStorage.setItem('users', JSON.stringify(users));
    localStorage.setItem('outcomes', JSON.stringify(outcomes));
    localStorage.setItem('customOutcomeTypes', JSON.stringify(customOutcomeTypes));
    console.log("Data saved.");
}

// --- 用户管理 ---
function validateLogin(username, password) {
    const user = users.find(u => u.username === username && u.password === password);
    return user ? { id: user.id, username: user.username, role: user.role } : null;
}

function getCurrentUser() {
    return JSON.parse(localStorage.getItem('currentUser'));
}

function setCurrentUser(user) {
    localStorage.setItem('currentUser', JSON.stringify(user));
}

function clearCurrentUser() {
    localStorage.removeItem('currentUser');
}

function getAllUsers() {
    return users;
}

function addUser(username, password, role) {
    if (users.some(u => u.username === username)) {
        return { success: false, message: '用户名已存在！' };
    }
    const newUser = {
        id: 'u' + Date.now().toString(36) + Math.random().toString(36).substr(2),
        username,
        password,
        role
    };
    users.push(newUser);
    saveData();
    return { success: true, message: '用户添加成功！' };
}

function updateUser(id, newUsername, newPassword, newRole) {
    const userIndex = users.findIndex(u => u.id === id);
    if (userIndex === -1) {
        return { success: false, message: '用户未找到！' };
    }
    if (users.some(u => u.username === newUsername && u.id !== id)) {
        return { success: false, message: '用户名已存在！' };
    }
    users[userIndex].username = newUsername;
    if (newPassword) { // Only update password if provided
        users[userIndex].password = newPassword;
    }
    users[userIndex].role = newRole;
    saveData();
    return { success: true, message: '用户更新成功！' };
}

function deleteUser(id) {
    // Prevent admin from deleting themselves if current user is admin
    const currentUser = getCurrentUser();
    if (currentUser && currentUser.id === id) {
        return { success: false, message: '无法删除当前登录用户！' };
    }
    const initialLength = users.length;
    users = users.filter(u => u.id !== id);
    if (users.length < initialLength) {
        saveData();
        return { success: true, message: '用户删除成功！' };
    }
    return { success: false, message: '用户未找到！' };
}

// --- 成果管理 ---
function getAllOutcomes() {
    return outcomes;
}

function addOutcome(outcomeData) {
    const newOutcome = {
        id: 'o' + Date.now().toString(36) + Math.random().toString(36).substr(2),
        submitterId: getCurrentUser().id,
        submitterUsername: getCurrentUser().username,
        submitDate: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
        status: '待审核', // New outcomes are always pending review
        ...outcomeData
    };
    outcomes.push(newOutcome);
    saveData();
    return { success: true, message: '成果提交成功，等待审核！', outcome: newOutcome };
}

function updateOutcome(outcomeId, updatedFields) {
    const index = outcomes.findIndex(o => o.id === outcomeId);
    if (index > -1) {
        outcomes[index] = { ...outcomes[index], ...updatedFields };
        saveData();
        return { success: true, message: '成果更新成功！', outcome: outcomes[index] };
    }
    return { success: false, message: '成果未找到！' };
}

function deleteOutcome(outcomeId) {
    const initialLength = outcomes.length;
    outcomes = outcomes.filter(o => o.id !== outcomeId);
    if (outcomes.length < initialLength) {
        saveData();
        return { success: true, message: '成果删除成功！' };
    }
    return { success: false, message: '成果未找到！' };
}

function approveOutcome(outcomeId) {
    return updateOutcome(outcomeId, { status: '已通过', reviewDate: new Date().toISOString().slice(0, 10) });
}

function rejectOutcome(outcomeId, reason) {
    return updateOutcome(outcomeId, { status: '已驳回', rejectionReason: reason, reviewDate: new Date().toISOString().slice(0, 10) });
}

// --- 成果类型管理 ---
function getOutcomeTypes() {
    // Return a copy to prevent direct modification of the internal array
    return [...defaultOutcomeTypes, ...customOutcomeTypes.filter(t => !defaultOutcomeTypes.some(dt => dt.id === t.id))];
}

function addCustomOutcomeType(name) {
    if (getOutcomeTypes().some(t => t.name === name)) {
        return { success: false, message: '该成果类型名称已存在！' };
    }
    const newTypeId = 'custom' + Date.now().toString(36) + Math.random().toString(36).substr(2);
    const newType = {
        id: newTypeId,
        name: name,
        requiredFields: [], // Custom types start with no specific fields, can be extended in a real system
        optionalFields: [],
        fieldLabels: {},
        fieldPlaceholders: {},
        fieldTypes: {},
        dropdownOptions: {},
        attachments: true,
        isCustom: true // Mark as custom
    };
    customOutcomeTypes.push(newType);
    saveData();
    return { success: true, message: '成果类型添加成功！', type: newType };
}

function deleteCustomOutcomeType(id) {
    // Prevent deleting default types
    if (defaultOutcomeTypes.some(t => t.id === id)) {
        return { success: false, message: '无法删除预设成果类型！' };
    }
    const initialLength = customOutcomeTypes.length;
    customOutcomeTypes = customOutcomeTypes.filter(t => t.id !== id);
    if (customOutcomeTypes.length < initialLength) {
        saveData();
        return { success: true, message: '成果类型删除成功！' };
    }
    return { success: false, message: '成果类型未找到！' };
}

// Initial data load when script loads
loadData();

// Expose functions globally for simplicity in this prototype
window.data = {
    loadData,
    saveData,
    validateLogin,
    getCurrentUser,
    setCurrentUser,
    clearCurrentUser,
    getAllUsers,
    addUser,
    updateUser,
    deleteUser,
    getAllOutcomes,
    addOutcome,
    updateOutcome,
    deleteOutcome,
    approveOutcome,
    rejectOutcome,
    getOutcomeTypes,
    addCustomOutcomeType,
    deleteCustomOutcomeType
};
